<?php

namespace app\api\controller\wap;

use app\command\extend\http\ApiCache;
use app\common\model\Calculation;
use app\common\model\coin\CoinRuleCover;
use app\common\model\users\ProfitStatistics;
use app\common\model\users\UsersKey;
use app\common\model\users\UsersLog;
use mall\utils\Tool;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Cache;
use mall\basic\Users;

class CoinRule extends Base
{
    //交易页列表
    public function list() {
        try{
            $type = Request::get('type',0,'intval');
            $platform = Request::get('platform',1,'intval');
            $userid = \mall\basic\Users::get('id');
            //p($coinPlatform);exit;
            $coinModel = (new \app\common\model\coin\Coin());
            $coinRuleModel = (new \app\common\model\coin\CoinRule());
            $model = $coinRuleModel->alias('coin_rule');
            $model->where('coin.status',"=",$coinModel::STATUS_OPEN);
            $model->where('coin.platform',"=",$platform);
            //$model->where('coin_rule.is_open',"=",$coinRuleModel::STATUS_OPEN);
            $model->where('coin_rule.user_id',"=",$userid);
            //$model->where('coin_rule.user_id',"=",1);
            if($type>0) {
                $model->where('coin_rule.type',"=",$type);
            }
            $coinRuleList= $model
                ->join('coin coin','coin.id=coin_rule.coin_id','INNER')
                ->join('coin_rule_run run_details','run_details.id=coin_rule.coin_rule_run_id AND run_details.unique_id=run_details.coin_rule_id','LEFT')
                ->field([
                    'coin.id','coin.name','coin.code',
                    'coin_rule.type','coin_rule.is_open','coin_rule.coin_id','coin_rule.first_amount','coin_rule.num','coin_rule.stop_profit_ratio','coin_rule.stop_profit_callback',
                    'run_details.unique_id','run_details.cover_times','run_details.cover_times_auto',
                    'run_details.cover_times_manual','run_details.amount','run_details.quantity','run_details.unit_price','run_details.version'
                ])
                ->select();
            //echo $model->getLastSql();
            $coinList = $coinModel->field('id,name,code,order_num')
                ->where([['status','=',$coinModel::STATUS_OPEN],['platform','=',$platform]])
                ->select();
            $coinRuleList = $coinRuleList?$coinRuleList->toArray():[];
            //p($coinRuleList);exit;
            $coinList = $coinList?$coinList->toArray():[];
            if($coinList) {
                if(!$marketTickers = ApiCache::request('GetHistoryOpenAndClose',[
                    'codes' => implode(',',array_column($coinList,'code')),
                ]))  {
                    $marketTickers = (new UsersKey())->getMarketTickers();
                }
                $coinList = array_column($coinList,null,'id');
                $coinRuleList = $coinRuleList?array_column($coinRuleList,null,'coin_id'):[];
                $tmpList = $issets = $orderNum = $isOpen = [];
                foreach ($coinList as $key=>$value) {
                    $id = $value['id'];
                    $tmpList[$id]['name'] = strtoupper($value['name']);
                    //交易对设置过
                    if(isset($coinRuleList[$value['id']])) {
                        $arrCoinRule = $coinRuleList[$value['id']];
                        $tmpList[$id]['id'] = $id;
                        $tmpList[$id]['num'] = sprintf("%.8f",$arrCoinRule['quantity']);
                        $tmpList[$id]['label'] = $arrCoinRule['is_open']==1?$coinRuleModel::getTypeText($arrCoinRule['type']):'未开启';
                        //涨幅
                        $tmpList[$id]['increase'] = ($arrCoinRule['unit_price']>0)?bcdiv(100*($marketTickers[$value['code']]['close'] -$arrCoinRule['unit_price']),$arrCoinRule['unit_price'],2):0;
                        //浮亏
                        $tmpList[$id]['profit'] = bcmul($tmpList[$id]['increase']*0.01,$arrCoinRule['amount'],2);
                        $tmpList[$id]['isset'] = 1;
                        $issets[]= $tmpList[$id]['isset'];
                        $orderNum[]= $value['order_num'];
                        $isOpen[]= 1;
                    } else {
                        if($type>0) {
                            unset($tmpList[$id]);
                        } else {
                            $tmpList[$id]['id'] = $id;
                            $tmpList[$id]['num'] = sprintf("%.8f",0);
                            $tmpList[$id]['label'] = '未设置';
                            $tmpList[$id]['profit'] = sprintf("%.2f",0);
                            $tmpList[$id]['increase'] = sprintf("%.2f",0);
                            $tmpList[$id]['isset'] = 0;
                            $issets[]= $tmpList[$id]['isset'];
                            $orderNum[]= $value['order_num'];
                            $isOpen[]= 0;
                        }
                    }
                }
                //Log::log('notice',$tmpList);
                array_multisort($issets, SORT_DESC,$orderNum, SORT_ASC,$isOpen, SORT_DESC, $tmpList);
                //p($coinList);exit;
                //查询账户余额
                $data['list'] = $tmpList;
            } else {
                $data['list'] = [];
                return $this->returnAjax("暂无数据",0,$data);
            }
            $userKeyInfo = (new UsersKey())->alias('key')
                ->join('users user','user.id=key.id','INNER')
                ->field('key.id,key.account_id,key.access_key,key.secret_key,user.vip,user.vip_expire,user.local_balance,user.has_service_charge')
                ->where([['user_id','=',$userid]])
                ->find();
            if($userKeyInfo) {
                $userKeyInfo = $userKeyInfo->toArray();
                $data['account_balance'] = (new UsersKey)->getAccountBalance($userKeyInfo,true);
            } else {
                $data['account_balance'] = sprintf('%0.2',4);
            }

            $data['isMonitor'] = $userKeyInfo?\app\common\model\users\Users::isMonitor($userKeyInfo):false;
            $data['account_balance'] = (new UsersKey)->getAccountBalance($userKeyInfo,true);
            return $this->returnAjax("ok",1,$data);
        }catch (\Exception $e) {
            return $this->returnAjax('系统内部错误'.$e->getMessage(),0);
        }
    }

    public function detail() {
        try{
            $id = Request::get('id',0,'intval');
            $coinModel = (new \app\common\model\coin\Coin());
            $coinRuleModel = (new \app\common\model\coin\CoinRule());
            $coinRuleRunModel = (new \app\common\model\coin\CoinRuleRun());
            $CoinRuleCoverModel = new CoinRuleCover();

            $name = $coinModel->field('name,code')->find($id);
            if(!$name) {
                return $this->returnAjax('无效交易对',0);
            }
            $model = $coinRuleModel->alias('a');
            $model->where('a.coin_id',"=",$id);
            $model->where('a.user_id',"=",\mall\basic\Users::get('id'));
            $coinRuleDetail = $model
                ->leftjoin('coin_rule_run b', 'a.coin_rule_run_id=b.id AND b.unique_id=b.coin_rule_id')
                ->field('a.*,b.cover_times_auto as cover_times,b.cover_times_auto,b.cover_times_manual,b.amount,b.quantity,b.unit_price,b.version')
                ->order('a.id','DESC')
                ->find();

            $coinRuleDetail = $coinRuleDetail?$coinRuleDetail->toArray():[];
            $data['name'] = strtoupper(str_replace('/USDT','',$name->name));
            // 通过缓存火币中间系统获取行情
            if(!$marketTickers = ApiCache::request('GetHistoryOpenAndClose',[
                'codes' => $name->code,
            ]))  {
                $marketTickers = (new UsersKey())->getMarketTickers();
            }

            //p($coinRuleDetail);exit;
            //Log::log('notice',$coinRuleDetail);
            if($coinRuleDetail) {
                $data['id'] = $coinRuleDetail['id'];
                $data['coin_rule_run_id'] = $coinRuleDetail['coin_rule_run_id'];
                $data['trade_rule'] = $coinRuleDetail['trade_rule'];
                $data['amount'] = isset($coinRuleDetail['amount'])?sprintf("%.8f",$coinRuleDetail['amount']):sprintf("%.8f",0);
                if(isset($coinRuleDetail['unit_price'])) {
                    if(isset($coinRuleDetail['unit_price']) && $coinRuleDetail['unit_price']<1000) {
                        $data['unit_price'] = sprintf("%.6f",$coinRuleDetail['unit_price']);
                    } if(isset($coinRuleDetail['unit_price']) && $coinRuleDetail['unit_price']>=1000 && $coinRuleDetail['unit_price']<10000) {
                        $data['unit_price'] = sprintf("%.4f",$coinRuleDetail['unit_price']);
                    }if(isset($coinRuleDetail['unit_price']) && $coinRuleDetail['unit_price']>=10000) {
                        $data['unit_price'] = sprintf("%.2f",$coinRuleDetail['unit_price']);
                    }
                } else {
                    $data['unit_price'] = sprintf("%.6f",0);
                }

                $data['quantity'] = isset($coinRuleDetail['quantity'])?sprintf("%.6f",$coinRuleDetail['quantity']):sprintf("%.6f",0);
                $data['current_price'] = $marketTickers[$name->code]['close'];
                $data['profit'] = ($coinRuleDetail['unit_price']>0)?bcdiv($data['current_price'] -$coinRuleDetail['unit_price'],$coinRuleDetail['unit_price'],4):sprintf("%.4f",0);
                //$data['profit'] = 0.000;

                $data['increase'] = bcmul($data['profit'],$coinRuleDetail['unit_price'],3);
                $data['cover_times'] = isset($coinRuleDetail['cover_times'])?$coinRuleDetail['cover_times']:0;
                $data['first_amount']= isset($coinRuleDetail['first_amount'])?$coinRuleDetail['first_amount']:0;
                $data['stop_profit_ratio']= isset($coinRuleDetail['stop_profit_ratio'])?$coinRuleDetail['stop_profit_ratio']:0;

                $data['num']= isset($coinRuleDetail['num'])?$coinRuleDetail['num']:0;
                $data['version']= isset($coinRuleDetail['version'])?$coinRuleDetail['version']:0;
                $data['stop_profit_callback']= isset($coinRuleDetail['stop_profit_callback'])?$coinRuleDetail['stop_profit_callback']:0;
                //$data['cover_callback']= isset($coinRuleDetail['cover_callback'])?$coinRuleDetail['cover_callback']:0;
                $coinRuleCover = $CoinRuleCoverModel->field('overlap,callback')
                    ->where('coin_rule_id',$coinRuleDetail['id'])->where('frequency',$coinRuleDetail['cover_times']+1)->find();
                $coinRuleCover = $coinRuleCover?$coinRuleCover->toArray():[];
                $data['overlap']=$coinRuleCover?$coinRuleCover['overlap']:0;
                $data['callback']=$coinRuleCover?$coinRuleCover['callback']:0;

            } else {
                $data['coin_rule_run_id'] = 0;
                $data['id'] = 0;
                $data['amount'] = sprintf("%.8f",0);
                $data['unit_price'] = sprintf("%.6f",0);
                $data['quantity'] = sprintf("%.6f",0);
                $data['current_price'] = $marketTickers[$name->code]['close'];
                $data['profit'] = sprintf("%.4f",0);
                $data['increase'] = bcmul($data['profit'],$data['unit_price'],3);
                $data['cover_times'] = 0;
                $data['first_amount']= 0;
                $data['num']= 0;
                $data['version']= 0;
                $data['stop_profit_callback'] = 0;
                $data['stop_profit_ratio']= 0;
                $data['callback']=0;
                $data['overlap']=0;
            }
            $data['type'] = isset($coinRuleDetail['type'])?$coinRuleDetail['type']:0;
            $data['is_open'] = isset($coinRuleDetail['is_open'])?$coinRuleDetail['is_open']:2;
            if(isset($coinRuleDetail['is_first_double'])){
                $data['is_first_double'] = $coinRuleDetail['is_first_double']==1?true:false;
                $data['overlap_arr'] =$coinRuleModel->coinRuleCover()->field('frequency,overlap')->where('coin_rule_id',$coinRuleDetail['id'])
                    ->select()
                    ->toArray();
            } else {
                $data['is_first_double'] = false;
                $data['overlap_arr'] = [];
            }
            $data['cover_callback'] = isset($coinRuleDetail['cover_callback'])?$coinRuleDetail['cover_callback']:0;
            return $this->returnAjax("ok",1,$data);
        }catch (\Exception $e) {
            return $this->returnAjax('系统内部错误'.$e->getMessage(),0);
        }

    }

    //交易规则绑定
    public function coinRuleBind(){
        try{
            $coinRuleModel = (new \app\common\model\coin\CoinRule());
            $params = array_map(function($value){return trim($value);},Request::post());
            validate([
                'first_amount'   => 'require',
                'coin_id'   => 'require',
                'num'  =>  'require',
                'stop_profit_ratio'  =>  'require',
                'stop_profit_callback'  =>  'require',
                'cover_callback'  =>  'require',
                'is_first_double'  =>  'require|min:1|max:2',
                'is_open'  =>  'require|min:1|max:2',
            ],[
                'first_amount'   => '请输入首单额度',
                'coin_id'   => '交易对id缺少',
                'num'  =>  '数量必填',
                'stop_profit_ratio'  =>  '止盈比例必填',
                'stop_profit_callback'  =>  '盈利回调必填',
                'cover_callback'  =>  '补仓回调必填',
                'is_first_double'  =>  '是否开仓加倍参数有误',
                'is_open'  =>  '开启参数有误',
            ])->check($params);

            $params['user_id'] = Users::get("id");
            $coinRuleCoverModel = new CoinRuleCover();
            $coinRuleModel->startTrans();
            if(strpos($params['coin_id'],',')!== false) {
                $isHave = $coinRuleModel->where('user_id',$params['user_id'])->Where('coin_id','in',$params['coin_id'])->column('id','coin_id');
                $coinRuleCoverArr = [];
                $callback = explode(',',$params['callback']);
                $coinIds = explode(',',$params['coin_id']);
                $updateCoinRules = $coinRules = $isHaveIds = [];
                foreach ($coinIds as $val) {
                    if(isset($isHave[$val])) {
                        array_push($isHaveIds,$isHave[$val]);
                    } else {
                        $coinRules[$val] = $params;
                        $coinRules[$val]['coin_id'] = $val;
                    }
                }
                //$updateCoinRules[$val] = $params;
                $updateCoinRules['num'] = (int)$params['num'];
                $updateCoinRules['user_id'] = Users::get("id");
                $updateCoinRules['first_amount'] = $params['first_amount'];
                $updateCoinRules['cover_callback'] = (float)$params['cover_callback'];
                $updateCoinRules['stop_profit_callback'] = (float)$params['stop_profit_callback'];
                $updateCoinRules['stop_profit_ratio'] = (float)$params['stop_profit_ratio'];
                /*Log::log('test',$updateCoinRules);
                Log::log('test',$isHaveIds);*/
                //Log::log('test',$isHaveIds);
                //已经存在的更新
                $coinRuleModel::update($updateCoinRules,[
                    ['id', 'in', $isHaveIds]
                ]);
                //不存在的插入
                $res = $coinRuleModel->insertAll($coinRules);
                $resIds =  $coinRuleModel->getLastInsID();
                $ids = array();
                for ($i=0; $i<$res; $i++) {
                    $ids[] = (int)$resIds++;
                }
                $ids = array_merge($ids,$isHaveIds);
                $coinRuleCoverModel->where('coin_rule_id','in',$ids)->delete();
                foreach ($ids as $ins_id) {
                    foreach ($callback as $key => $val) {
                        $coinRuleCoverArr[$ins_id.$key]['coin_rule_id'] = $ins_id;
                        $coinRuleCoverArr[$ins_id.$key]['frequency'] = $key + 1;
                        $coinRuleCoverArr[$ins_id.$key]['overlap'] = $val;
                        $coinRuleCoverArr[$ins_id.$key]['callback'] = $params['cover_callback'];
                    }
                }
                $coinRuleCoverModel->saveAll($coinRuleCoverArr);
                $coinRuleModel->commit();

                // 批量添加更新日志
                array_map(function($insId) use($params){
                    // 添加日志
                    UsersLog::logAdd('RULE_UPDATE',['params'=>UsersLog::encode($params)],$insId);
                },$ids);
                //$coinRuleModel->rollback();
                return $this->returnAjax("更新成功",1,[]);

            } else {
                $coinRule = $coinRuleModel->withSearch(['user_id','coin_id'], [
                    'user_id'	=>	$params['user_id'],
                    'coin_id'	=>	$params['coin_id']
                ])->find();
                $coinRule =  $coinRule?$coinRule->toArray():[];
                if($coinRule) {
                    $coinRuleModel::update($params,['id'=>$coinRule['id']]);
                    $insId = $coinRule['id'];
                } else {
                    $coinRuleModel->save($params);
                    $insId = $coinRuleModel->id;
                }
                if($params['callback']) {
                    $coinRuleCover = $coinRuleCoverModel->where('coin_rule_id',$insId)->select();
                    $coinRuleCover = $coinRuleCover?$coinRuleCover->toArray():[];
                    $updateCoinRuleCover = [];
                    $coinRuleCoverArr = array_column($coinRuleCover,null,'frequency');
                    /*Log::log('notice',$insId);
                    Log::log('notice',$coinRuleCoverArr);*/

                    $callback = explode(',',$params['callback']);
                    $time = time();
                    //Log::log('notice',$callback);
                    if($coinRuleCover) {
                        foreach ($coinRuleCover as $key=>$val) {
                            $coinRuleCoverArr[$val['frequency']]['callback'] = $params['cover_callback'];
                            $coinRuleCoverArr[$val['frequency']]['overlap'] = $callback[$val['frequency']-1];
                            $coinRuleCoverArr[$val['frequency']]['create_time'] = $coinRuleCoverArr[$val['frequency']]['update_time'] = $time;
                            $updateCoinRuleCover [] = $coinRuleCoverArr[$val['frequency']];
                        }
                        //Log::log('test1111',$updateCoinRuleCover);
                        $coinRuleCoverModel->saveAll($updateCoinRuleCover);
                        //Log::log('notice',$coinRuleModel->getLastSql());
                    } else {
                        $coinRuleCoverArr = [];
                        foreach ($callback as $key=>$val) {
                            $coinRuleCoverArr[$key]['coin_rule_id'] = $insId;
                            $coinRuleCoverArr[$key]['frequency'] = $key+1;
                            $coinRuleCoverArr[$key]['overlap'] = $val;
                            $coinRuleCoverArr[$key]['callback'] =$params['cover_callback'];

                        }

                        $coinRuleCoverModel->saveAll($coinRuleCoverArr);
                    }
                }
                $coinRuleModel->commit();

                // 添加日志
                UsersLog::logAdd('RULE_UPDATE',['params'=>UsersLog::encode($params)],$insId);

                return $this->returnAjax("操作成功",1,[]);
            }
        }catch (\Exception $e){
            $coinRuleModel->rollback();
            return $this->returnAjax('系统内部错误'.$e->getMessage().$e->getLine(),0);
        }
    }

    //设置规则参数 循环策略/交易对开关
    public function setRuleType() {
        try{
            $params = array_map(function($value){return trim($value);},Request::post());
            validate([
                'coin_id'   => 'require',
                'type'  =>  'min:1|max:2',
                'is_open'  =>  'min:1|max:2',
            ],[
                'coin_id'   => '交易对id缺少',
                'type'  =>  '策略类型有误',
                'is_open'  =>  '开启参数有误',
            ])->check($params);

            //批量设置
            if(strpos($params['coin_id'],',')!== false) {
                $map = [
                    ['coin_id', 'in', $params['coin_id']],
                    ['user_id', '=', Users::get("id")],
                ];
            } else {
                $map = [
                    ['coin_id', '=', $params['coin_id']],
                    ['user_id', '=', Users::get("id")],
                ];
            }
            $coinRuleModel = (new \app\common\model\coin\CoinRule());
            unset($params['coin_id']);
            $coinRuleModel::update($params,$map,['type','is_open','trade_rule']);
            // 获取ID集合
            $ids = $coinRuleModel->where($map)->column('id');
            array_map(function($id)use($params){
                // 添加日志
                UsersLog::logAdd('RULE_UPDATE_TYPE_OR_OPEN',['params'=>UsersLog::encode($params)],$id);
            },$ids);
            return $this->returnAjax("更新成功",1,[]);
        }catch (\Exception $e){
            return $this->returnAjax('系统内部错误'.$e->getMessage().$e->getLine(),0);
        }
    }

    public function getRuleTips() {
        $page = Request::get('page',1,'intval');
        $pageSize = Request::get('pagesize',15,'intval');
        $model = new \app\common\model\coin\CoinRuleRunTips();
        $model = $model->where('user_id',"=",\mall\basic\Users::get('id'));
        $list = $model
            ->field('type,message,create_time,coin_name')
            ->order('id','DESC')
            ->limit(($page-1)*$pageSize,$pageSize)
            ->select();
        $data['list'] = $list?$list->toArray():[];
        return $this->returnAjax("ok",1,$data);
    }


    public function getTradeLog() {
        $params = array_map(function($value){return trim($value);},Request::get());
//        if(!isset($params['rule_id'])) {
//            return $this->returnAjax("参数确失",0,[]);
//        }
        $page = Request::get('page',1,'intval');
        $pageSize = Request::get('pagesize',10,'intval');
        $model = new \app\common\model\coin\CoinRuleRunTrade();
        $model = $model
            ->alias('a')
            ->where('a.user_id',"=",\mall\basic\Users::get('id'))
            ->where('a.status',"=",5)
            ->join('coin_rule_run b','b.id=a.coin_rule_run_id','left');
            //->where('a.coin_rule_id',$params['rule_id'])
            //->where('a.cover_times','>=',0);
        if(isset($params['rule_id'])&&$params['rule_id']>0) {
            $model = $model->where('a.coin_rule_id',$params['rule_id']);
        }
        if(isset($params['type'])&&$params['type']>0) {
            $model = $model->where('a.type','=',$params['type']);
        }
        if(isset($params['start_time'])) {
            $model = $model->where('a.update_time','>=',strtotime($params['start_time'].' 00:00:00'));
        }
        if(isset($params['end_time'])) {
            $model = $model->where('a.update_time','<=',strtotime($params['end_time'].' 23:59:59'));
        }
        if($list = $model
            ->field('b.amount,a.*,((a.field_price-b.unit_price)*(a.field_quantity+ a.reserved_quantity) - a.field_fees) as profit')
            ->order('a.id','DESC')
            ->limit(($page-1)*$pageSize,$pageSize)
            ->select()){
            $tmpList = [];  //临时列表
            foreach($list as $key=>$value) {
                $value = $value->getData();
                if($value) {
                    $tmpList[$key] = $value;
                    $tmpList[$key]['field_quantity'] = $value['field_quantity'] + $value['reserved_quantity'];
                    $tmpList[$key]['field_amount'] = $value['field_amount'] + $value['reserved_quantity']*$value['reserved_price'];
                    $tmpList[$key]['field_price'] = sprintf("%.6f",$tmpList[$key]['field_amount']/$tmpList[$key]['field_quantity']);
                    $tmpList[$key]['coin_name'] = strtoupper($value['coin_name']);
                    $tmpList[$key]['create_time'] = date('Y-m-d H:i:s',$value['update_time']);
                }
            }
        }
        //$data['list'] = $list?$list->toArray():[];
        $data['list'] = $tmpList;

        return $this->returnAjax("ok",1,$data);
    }

    //手动补仓 coin_rule_id、coin_rule_run_id、unit_price amount price
    public function dealOrder() {
        $post = Request::post();
        $params = [];
        try {
            // 可编辑参数验证
            $editFields = [
                'coin_rule_id'   => ['require','规则确少'],
                'coin_rule_run_id'  => ['require','规则运行参数确少'],
                'unit_price'  => ['require','单价缺少'],
                'amount'   => ['require','数量缺少缺少'],
                'price'   => ['require','购买单价缺少'],
                'type'   => ['require','类型缺少'],
                'version' => ['require','版本确少']
            ];
            foreach($post as $key=>$value) {
                if(array_key_exists($key,$editFields)) {
                    $params[$key] = trim($value);
                    validate([$key=>$editFields[$key][0]],[$key=>$editFields[$key][1]])->check($params);
                }
            }
            //1手动补仓 2手动清仓
            if($params['type']==1) {
                (new Trade())->coverOrder($params,$params['amount'],$params['version']);
            } else if($params['type']==2) {
                (new Trade())->clearanceOrder($params,$params['price']);
            }
            UsersLog::logAdd($params['type']==1?'COVER_ORDER':'CLEARANCE_ORDER',['params'=>UsersLog::encode($params)],$params['coin_rule_id']);
            return $this->returnAjax("操作成功",1);
        } catch (\Exception $e){
            $info = '刷新重试'.$e->getMessage().$e->getLine();
            switch($e->getMessage()) {
                case 'MONITOR':
                    $info = '无会员或平台余额小于 5 USDT';
                    break;
                case 'ACCOUNT_NOT_EXIST':
                    $info = '账号信息错误，请检测绑定平台的密钥信息';
                    break;
                case 'BALANCE_ERROR':
                    $info = '火币账号余额不足';
                    break;
                case 'REFRESH':
                case 'SYSTEM':
                case 'UNKNOWN':
                case 'CLIENT_ID_ERROR':
                case 'SYMBOL_DISABLED_FOR_USER':
                case 'SYMBOL_DISABLED':
                case 'SYSTEM_ERROR':
                case 'NETWORK':
                    $info = '数据变化，请刷新重试';
                    break;
            }
            return $this->returnAjax($info,0);
        }
    }

    //type 1是查看累计盈利 2是查看今日盈利
    public function billLog() {


        $page = Request::get('page',1,'intval');
        $pageSize = Request::get('pagesize',10,'intval');
        $type = Request::get('type',1,'intval');
        $model = new \app\common\model\coin\CoinRuleRunTrade();
        $uid = Users::get('id');
        $tmpList = [];  //临时列表

        //$uid = 5;
        if($type==2) {
            $startTime = strtotime(date('Y-m-d',time()).' 00:00:00');
            $endTime = strtotime(date('Y-m-d',time()).' 23:59:59');
            if($list = $model->alias('a')
                ->join('coin_rule_run b','b.id=a.coin_rule_run_id','left')
                ->where('a.user_id',$uid)
              //  ->where('a.type',2)
                ->where('a.statistics',$model::JOIN_STATISTICS_LIST['JOIN'])
                ->where('a.field_time','>=',$startTime)
                ->where('a.field_time','<=',$endTime)
                ->field('b.amount,a.order_id,a.coin_name,a.unit,a.create_time,' .
             //   ((a.field_price-b.unit_price)*(a.field_quantity+ a.reserved_quantity) - a.field_fees) as profit,
                    'a.field_price,a.field_quantity,a.reserved_quantity,a.field_fees,b.unit_price'
                )
                ->order('a.id','DESC')
                ->limit(($page-1)*$pageSize,$pageSize)
                ->select()){
                //p($list);exit;
                foreach($list as $key=>$value) {
                    $value = $value->getData();
                    // 统一盈利计算公式
                    $value['profit'] = Calculation::profit($value);
                    //Log::log('test',$value);
                    if($value && bccomp($value['profit'],0,20) == 1) {
                        $tmpList[$key] = $value;
                        $tmpList[$key]['profit'] = sprintf('%.6f',$value['profit']);
                        $tmpList[$key]['name'] = strtoupper($value['coin_name']).'/'.$value['unit'];
                        $tmpList[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
                    }
                }
            }

            //$data['list'] = $list?$list->toArray():[];
        } else {
            if($list = (new ProfitStatistics())->recordAll([
                'user_id'   => $uid,
                'type'  => ProfitStatistics::TYPE_LIST['DAY']
            ],[($page-1)*$pageSize,$pageSize],['date'=>'DESC'],['date','profit'])){
                foreach($list as $key=>$value) {
                    if(bccomp($value['profit'],0,20) == 1) {
                        $tmpList[$key] = [
                            'time'  => $value['date'],
                            'profit'    => Calculation::trimZero($value['profit'],6)
                        ];
                    }
                }
            }
        }


        $tmpList = array_values($tmpList);


        $data['totalProfit'] = 0;
        $data['todayProfit'] = 0;
        $data['list'] = $tmpList;
        $dateList = explode(' ',date(' Y-m-d'));
        $list = (new ProfitStatistics())->unionByDate($dateList,$uid,['date','profit']);
        foreach ($list as $value) {
            if($value['date'] == '') {
                $data['totalProfit'] = Calculation::trimZero($value['profit'],6);
            } else if($value['date'] == $dateList[1]) {
                $data['todayProfit'] = Calculation::trimZero($value['profit'],6);
            }
        }

        return $this->returnAjax("ok",1,$data);
    }

}
